<template>
  <div class="myReviewContainer">
    <approval :dialogVisible="dialogVisible"
              :approvalName="approvalName"
              v-on:closeApprovalDialog="closeApprovalDialog"
              v-on:commitApproval="commitApproval"></approval>
    <div class="headerMenu">
      <split-vertical title="采购单列表"></split-vertical>
      <v-form :formProps="searchForm" ref="form"
              v-on:handleReset="handleReset"
              v-on:coverFormData="coverFormData">
      </v-form>
    </div>
    <notice v-if="isNotice" @closeTip="closeTip" :noticeVal="row"></notice>
    <div class="stand">
      <div style="line-height:50px;margin-left:10px;">
        <v-button :operationBtnArray="operationBtnArray" v-on:handleSearchTopBtn="handleSearchTopBtn"></v-button>
      </div>
      <div style="margin:0 10px;">
        <v-table :tableParams="tableParams" v-on:handleOperation="handleOperation"></v-table>
      </div>
    </div>
    <div class="pagination">
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-sizes="[10]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount">
        </el-pagination>
      </div>
    </div>
    <upload v-if="show" :id="id" @closeUpload="closeUpload"></upload>
    <el-dialog title="打款信息" width="70%" :visible.sync="dialogTableVisible">
      <v-table :tableParams="chRemitList" v-on:handleOperation="operation"></v-table>
      <el-dialog
        width="30%"
        title="采购打款审批"
        :visible.sync="innerVisible"
        append-to-body>
        <v-form :formProps="confirmForm" ref="form"
                v-on:handleReset="Reset"
                v-on:coverFormData="formData"></v-form>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
  let purOrderTypeData = {
    '1': '常规订单',
    '2': '集采订单',
    '3': '天猫订单'
  }
  let purBillsTypeData = {
    "0": "待处理",
    "1": "待初审",
    "2": "待终审",
    "3": "初审驳回",
    "4": "终审成功",
    "5": "终审驳回",
    "6": "批量入库",
    "7": "已取消",
  }
  let remitTypeValue = {
    '1': '全款',
    '2': '预付款',
    '3': '尾款',
    '4': '质保金',
    '5': '其他'
  };
  import VTable from "components/common/PageTable/VTable"
  import VForm from "components/common/VForm"
  import VButton from "components/common/VButton"
  import SplitVertical from "components/common/SplitVertical"
  import Approval from "components/common/Approval"
  import {localStorage} from 'js/localStorage'
  import upload from "components/base/upload"
  import Notice from 'components/base/billOrder/notice.vue'
  import axios from 'axios'

  const billStatusList = [
    {value: '0', label: '待处理'},
    {value: '1', label: '待初审'},
    {value: '2', label: '待终审'},
    {value: '3', label: '初审驳回'},
    {value: '4', label: '终审成功'},
    {value: '5', label: '终审驳回'},
    {value: '6', label: '已确认收货'},
    {value: '7', label: '已取消'}
  ];
  let approveStatus = {
    '1': "待初审",
    '2': "待终审",
    '3': "初审驳回",
    '4': "终审成功",
    '5': "终审驳回"
  }
  export default {
    components: {
      VTable, VForm, VButton, SplitVertical, Approval, upload, Notice
    },
    data() {
      return {
        dialogTableVisible: false,
        innerVisible: false,
        isAudit: false,
        showInvoice: false,
        isNotice: false,
        show: false,
        row: '',
        approvalUserId: '',
        approvalName: '',
        dialogVisible: false,
        operationBtnArray: [{
          text: '刷新',
          show: true,
          icon:'el-icon-refresh',
          type: 'primary',
          methodName: 'refresh',
        }, {
          text: '新增',
          show: true,
          type: 'success',
          icon:'el-icon-plus',
          methodName: 'add',
        },
          {
            text: '导出',
            icon: 'el-icon-download',
            show: true,
            type: 'warning',
            methodName: 'exportBuyExcel',
          }],
        searchForm: {
          col: 4,
          labelWidth: '100px',
          submitBtn: {
            text: '搜索'
          },
          formItemArray: [{
            label: '开始时间',
            prop: 'startTime',
            placeholder: "请选择计划开始时间",
            itemType: 'dateTime',
            value: ''
          }, {
            label: '结束时间',
            prop: 'endTime',
            placeholder: "请选择计划结束时间",
            itemType: 'dateTime',
            value: ''
          }, {
            label: '单据状态',
            placeholder: "请选择",
            prop: 'purBillsType',
            itemType: 'select',
            options: [],
            value: ''
          }, {
            label: '供应商',
            placeholder: "请选择",
            prop: 'supplyId',
            itemType: 'select',
            options: [],
            value: ''
          }, {
            label: '申请人',
            placeholder: "请输入",
            prop: 'username',
            value: ''
          }, {
            label: '单据编号',
            placeholder: "请输入单据(合同)编号",
            prop: 'purBillsId',
            value: ''
          }],
        },
        //分页
        searchCondition: {},
        pageIndex: 1,
        pageSize: 10,
        pageCount: null,
        //商品详情
        userId: '',
        purBillsId: '',
        tableParams: {
          operationColumnWidth: 330,
          dataArray: [],
          showMultiSelection: false,
          columnArray: [
            {label: '订单类型', prop: 'purOrderType', sortable: false, width: '80'},
            {label: '单据(合同)编号', prop: 'purBillsId', width: '120', sortable: false},
            {label: '单据状态', prop: 'purBillsType', sortable: false, width: "80"},
            {label: '创建时间', prop: 'createtime', sortable: false},
            {label: '订单总金额', prop: 'totalPrice', sortable: false, width: '100'},
            {label: '采购商品金额', prop: 'price', sortable: false, width: "110"},
            {label: '手动调整费用', prop: 'adjustMoney', sortable: false, width: "110"},
            {label: '其他总费用', prop: 'elsePrice', sortable: false, width: "100"},
            {label: '总采购数量', prop: 'total', sortable: false, width: "100"},
            {label: '订单日期', prop: 'purBillsDate', sortable: false},
            {label: '采购公司', prop: 'companyName', sortable: false},
            {label: '仓库', prop: 'depotName', sortable: false},
            {label: '供应商', prop: 'supplyName', sortable: false},
            {label: '申请人', prop: 'name', sortable: false, width: "80"}
          ],
          rowHandle: {}
        },
        chRemitList: {
          operationColumnWidth: 150,
          dataArray: [],
          showMultiSelection: false,
          columnArray: [
            {label: '打款日期', prop: 'remitDate', sortable: false, width: '80'},
            {label: '打款类型', prop: 'remitType', width: '120', sortable: false},
            {label: '打款金额', prop: 'remitMoney', sortable: false, width: "80"},
            {label: '打款公司', prop: 'companyName', sortable: false},
            {label: '收款公司', prop: 'supplyName', sortable: false, width: '100'},
            {label: '收款账号', prop: 'supplyAccount', sortable: false, width: "110"},
            {label: '开户行', prop: 'supplyAccountName', sortable: false, width: "110"},
            {label: '审批状态', prop: 'approveState', sortable: false, width: "100"},
            {label: '申请人', prop: 'username', sortable: false, width: "100"},
            {label: '备注', prop: 'approveIdea', sortable: false}
          ],
          rowHandle: {}
        },
        confirmForm: {
          resetBtn: {
            text: '取消',
          },
          col: 1,
          labelWidth: '90px',
          formItemArray: [{
            label: '审批结果',
            placeholder: "请选择",
            rules: [{required: true, message: '请选择审批结果', trigger: 'change'}],
            prop: 'approveResult',
            itemType: 'select',
            options: [
              {value: '1', label: '通过'},
              {value: '2', label: '驳回'}
            ],
            value: ''
          }, {
            label: '审批意见',
            prop: 'memo',
            itemType: 'textarea',
            value: ''
          }]
        },
        id: '',
        //审批需要的数据
        rowData: {}
      }
    },
    mounted() {
      if (this.$route.query.searchCondition) {
        this.searchCondition = Object.assign({}, JSON.parse(this.$route.query.searchCondition));
        this.searchForm.formItemArray.forEach(item => {
          for (let key in this.searchCondition) {
            if (item.prop === key) {
              item.value = this.searchCondition[key];
            }
          }
        });
        this.pageIndex = this.searchCondition.pageIndex;
      }
      this.init();
    },
    methods: {
      closeApprovalDialog() {
        this.dialogVisible = false;
      },
      cancelApproval() {
        let param = {
          purBillsId: this.purBillsId
        };
        let success = data => {
          if (data.code === 'OK') {
            this.dialogVisible = false;
            this.tips.MessageModal('success', '取消成功!');
            this.refresh();
          } else {
            this.$message.error(data.msg)
          }
        };
        this.api.cancelApproval(param, success)
      },
      //关闭弹窗
      closeTip() {
        this.isNotice = false;
      },
      commitApproval(valueArray) {
        let param = {
          approvalList: valueArray,
          purBillsId: this.purBillsId
        };
        let success = data => {
          if (data.code === 'OK') {
            this.dialogVisible = false;
            this.tips.MessageModal('success', '审批申请成功!');
            this.refresh();
          } else {
            this.$message.error(data.msg)
          }
        };
        this.api.approvalRequest(param, success)
      },
      closeUpload() {
        this.show = false
      },
      coverFormData(data) {
        this.searchCondition = data;
        this.pageIndex = 1;
        this.purchaseOrderList();
      },
      handleReset(formName) {
        this.$refs.form.resetForm(formName);
      },
      Reset(formName) {
        this.$refs.form.resetForm(formName);
        this.dialogVisible = false;
      },
      handleSearchTopBtn(methodName) {
        if (methodName === "refresh") {
          this.refresh();
        } else if (methodName === "exportBuyExcel") {
          this.exportExcel();
        } else {
          this.create();
        }
      },
      exportExcel() {
        axios({
          method: 'post',
          url: '/api/erp/v1/pur/export',
          responseType: 'blob',
          timeout: 1000 * 60 * 10,
          data: this.searchCondition
        }).then(res => {
          if (res.status === 200) {
            const link = document.createElement('a')
            let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', '采购单' + '.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            this.reload()
          } else {
            this.$message.error("数据错误")
          }
        }).catch(error => {

        })
      },
      init() {
        //供应商下拉列表
        this.getSupply();
        this.userId = localStorage.get('userID');
        this.purchaseOrderList();
      },
      operation(rowIndex, row, methodName) {
        if (methodName === "view") {
          this.$router.push({
            path: '/bill-order-pay-view',
            query: {
              purBillsId: row.purBillsId,
              id: row.id,
            }
          })
        } else if (methodName === 'delete') {
          this.tips.ConfirmModal('确认要删除吗？', () => {
            this.deleteInfo(row.id);
          });
        } else {
          this.innerVisible = true
          this.rowData = row
        }
      },
      deleteInfo(id) {
        let params = {
          id: id
        }
        let success = data => {
          if (data.code === 'OK') {
            this.tips.MessageModal('success', '删除成功！');
            this.chremit()
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.purInvoiceremitDelete(params, success)
      },
      handleOperation(rowIndex, row, methodName) {
        this.row = row;
        if (methodName === "view") {
          this.check();
        } else if (methodName === 'delete') {
          this.tips.ConfirmModal('确认要删除吗？', () => {
            this.delete(row.id);
          });
        } else if (methodName === 'update') {
          if (this.userId + '' !== row.userId + '') {
            this.tips.MessageModal('warning', '抱歉，您无法操作,采购申请人与登录人不是同一人！');
            return;
          }
          this.$router.push({
            path: '/order-info',
            query: {action: 'edit', purBillsId: row.purBillsId, searchCondition: JSON.stringify(this.searchCondition)}
          });
        } else if (methodName === 'approval') {
          this.approvalName = row.name;
          this.purBillsId = row.purBillsId;
          this.approvalUserId = row.userId;
          this.dialogVisible = true;
        } else if (methodName === 'uploadFile') {
          this.id = row.id
          this.uploadFile()
        } else if (methodName === 'notice') {
          this.isNotice = true;
        } else if (methodName === 'noticeRecord') {
          this.dialogTableVisible = true
          this.purBillsId = row.purBillsId;
          this.chremit()
        } else {
          this.tips.ConfirmModal('确认要取消审批申请吗？', () => {
            this.purBillsId = row.purBillsId;
            this.cancelApproval();
          });
        }
      },
      chremit() {
        this.chRemitList.dataArray = [];
        let params = {
          purBillsId: this.purBillsId,
          userId: localStorage.get("userID")
        }
        let success = data => {
          if (data.code === "OK") {
            this.chRemitList.dataArray = data.data.chRemitList;
            data.data.chRemitList.forEach(ele => {
              ele.remitType = remitTypeValue[ele.remitType]
              ele.approveState = approveStatus[ele.approveState]
              ele.remitDate = this.formatSystemDate(ele.remitDate)
              this.createRowHandle(ele);
            })
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.erpInvoiceGet(params, success)
      },
      createRowHandle(ele) {
        const approvalBtn = {
          text: '审批',
          show: true,
          type: 'text',
          methodName: 'examine'
        };
        ele.handleBtnArray = [{
          text: '查看',
          show: true,
          type: 'text',
          methodName: 'view'
        }, {
          text: '修改',
          show: false,
          type: 'text',
          methodName: 'update'
        }, {
          text: '删除',
          show: true,
          type: 'text',
          methodName: 'delete'
        }]
        if (ele.record) {
          ele.handleBtnArray.push(approvalBtn)
        }
      },
      uploadFile() {
        this.show = true
      },
      delete(purId) {
        let success = data => {
          if (data.code === 'OK') {
            this.tips.MessageModal('success', '删除成功！');
            this.purchaseOrderList();
          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.deletePurOrder(purId, success);
      },
      purchaseOrderList() {
        let param = this.searchCondition;
        if (!param.pageIndex || !param.pageSize) {
          param['pageIndex'] = this.pageIndex;
          param['pageSize'] = this.pageSize;
        }
        let success = data => {
          if (data.code === 'OK') {
            this.pageCount = data.pageCount;
            data.data.forEach(element => {
              this.buildRowHandle(element);
              if (element.elsePrice) {
                element.totalPrice = this.calculate.operation(element.price, element.elsePrice, '+');
              } else {
                element.totalPrice = element.price;
              }
              element.purOrderType = purOrderTypeData[element.purOrderType];
              element.purBillsDate = this.formatSystemDate(element.purBillsDate);
              element.createtime = this.formatSystemDate(element.createtime);
              element.purBillsType = purBillsTypeData[element.purBillsType];
            });
            this.tableParams.dataArray = data.data;
          } else {
            this.$message.error(data.msg);
          }
        };
        this.api.buyPurList(param, success);
      }, buildRowHandle(row) {
        const approvalBtn = {
          text: '发起审批',
          show: true,
          type: 'text',
          methodName: 'approval'
        };
        const cancelBtn = {
          text: '取消',
          show: true,
          type: 'text',
          methodName: 'cancel'
        };
        row.handleBtnArray = [{
          text: '查看',
          show: true,
          type: 'text',
          methodName: 'view'
        }, {
          text: '修改',
          show: true,
          type: 'text',
          methodName: 'update'
        }, {
          text: '删除',
          show: true,
          type: 'text',
          methodName: 'delete'
        }, {
          text: '上传',
          show: true,
          type: 'text',
          methodName: 'uploadFile'
        }, {
          text: '打款',
          show: true,
          type: 'text',
          methodName: 'notice'
        }, {
          text: '打款记录',
          show: true,
          type: 'text',
          methodName: 'noticeRecord'
        }];
        switch (row.purBillsType) {
          case "0":
          case "3":
          case "5":
          case "7":
            if (this.userId + '' !== row.userId + '') {
              return;
            }
            row.handleBtnArray.push(approvalBtn);
            break;
          case "1":
            if (this.userId + '' !== row.userId + '') {
              return;
            }
            row.handleBtnArray.push(cancelBtn);
            break;

        }
      },
      refresh() {
        this.purchaseOrderList();
      },
      create() {
        this.$router.push({
          path: '/order-info',
          query: {action: 'add'}
        })
      },
      getSupply() {
        let success = data => {
          if (data.code === 'OK') {
            this.searchForm.formItemArray.forEach(item => {
              if (item.prop === 'supplyId') {
                item.options = this.buildExceptKeyAndValue(data.data, "supplyName", "id", "label", "value");
              }
              if (item.prop === 'purBillsType') {
                item.options = billStatusList;
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        }
        this.api.getSupply({}, success);
      },
      check() {
        this.$router.push({
          path: '/my-review-detail',
          query: {
            action: 'edit',
            id: this.row.id,
            purBillsId: this.row.purBillsId,
            searchCondition: JSON.stringify(this.searchCondition)
          }
        })
      },
      //当前页
      handleCurrentChange(val) {
        this.pageIndex = val;
        this.searchCondition['pageIndex'] = val;
        this.purchaseOrderList();
      },
      //审批
      handleReset(formName) {
        this.$refs.form.resetForm(formName);
        this.innerVisible = false;
      },
      //审批
      formData(data) {
        data['type'] = this.rowData.record.type;
        data['id'] = this.rowData.record.id;
        data['remitId'] = this.rowData.id;
        data['purBillsId'] = this.rowData.purBillsId;
        data['approveId'] = this.rowData.approveId;
        data['remitStatus'] = this.rowData.approveState;
        let success = data => {
          if (data.code === "OK") {
            this.innerVisible = false;
            this.tips.MessageModal('success', '审批操作成功！');
            this.chremit()

          } else {
            this.$message.error(data.msg)
          }
        };
        this.api.remitConfirm(data, success)
      },
    },
  }
</script>
<style scoped>
  .el-dialog__wrapper {
    position: fixed;
    top: 20%;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: auto;
    margin: 0;
  }

</style>
<style lang="scss" scoped>
  .myReviewContainer {
    .pagination {
      text-align: right;
      padding:10px 0;
    }

    .table {
      margin-top: 10px;
      background: #fff;
    }
  }
</style>

